<template>
    <div class="flex_col_start card m5 p10">
        <label class="flex_center_self">串口设置</label>
        <div class="flex_row_center mt10">
            <label>串口</label>
            <el-select class="ml5 sel" v-model="ctx.selectPort">
                <el-option v-for="(item, index) in ctx.availablePorts" :key="index" :value="item" :label="item" />
            </el-select>
            <el-button @click="onClickOpen" class="ml5" type="primary">{{ ctx.openText }}</el-button>
        </div>
        <div class="flex_row_center mt10">
            <label>控制板</label>
            <el-select class="ml5 sel2" v-model="ctx.pingAddress">
                <el-option
                    v-for="(item, index) in devices"
                    :key="index"
                    :label = item.name
                    :value = item.address
                />
            </el-select>
            <el-button class="ml5" @click="onClickPing" type="primary">Ping</el-button>
        </div>
    </div>
</template>

<script lang="ts" setup>
import { devices, ipc, weight } from '@/service/address';
import { availablePorts, closeSerialPort, macAddress, openSerialPort, ping, serialPortIsOpen } from '@/service/system';
import { runAction } from '@/utils/ui';
import { reactive } from 'vue';

interface Ctx {
    availablePorts: string[],
    selectPort: string,
    openText: string,
    pingAddress: number,
}

const ctx = reactive<Ctx>({
    availablePorts: [],
    selectPort: '',
    openText: '打开',
    pingAddress: weight.address,
});

async function update() {
    const ret = await serialPortIsOpen();
    if (ret) {
        ctx.openText = '关闭';
    } else {
        ctx.openText = '打开';
    }
}

async function init() {
    ctx.availablePorts = await availablePorts();
    if (ctx.availablePorts.length != 0) {
        ctx.selectPort = ctx.availablePorts[0];
    }
    await update();
}

async function onClickOpen() {
    const ret = await serialPortIsOpen();
    if (ret) {
        await runAction('关闭串口', '', async () => {
            await closeSerialPort();
            await update();
        });
        return;
    }

    await runAction('打开串口', '', async () => {
        const name = ctx.selectPort;
        if (name.length == 0) {
            throw '没有选择串口';
        }
        await openSerialPort(name, 115200);
        await update();
    });
}

async function onClickPing() {
    await runAction('Ping', '', async () => {
        const dst = ctx.pingAddress;
        if (dst == ipc.address) {
            return;
        }
        await ping(dst);
    });
}

init();

</script>

<style scoped>
.sel {
    width: 100px;
}
.sel2 {
    width: 180px;
}
</style>
